import axios from "axios";
import Store from "@/stores";
import Router from "@/router";
const { LoadingBar } = window;
// axios.defaults.baseURL = process.env.baseURL;
// axios.defaults.timeout = 60000 * 2; //超时时间
const baseURL = "";
const service = axios.create({
  baseURL: baseURL || process.env.baseURL, // api base_url
  timeout: 30000, // 请求超时时间
});
const err = error => {
  LoadingBar.error();
  console.log("拦截器error", error);
  if (
    error.code === "ECONNABORTED" ||
    error.message === "Network Error" ||
    error.message.includes("timeout")
  ) {
    // $message.error("请求超时，请稍后重试");
    return Promise.resolve({
      code: 408,
      message: "请求超时，请稍后重试",
    });
  } else if (error.message.includes("中断请求")) {
    return;
  }
  return Promise.resolve({
    code: 500,
    message: "网络异常",
  });
};
// response interceptor
service.interceptors.response.use(response => {
  LoadingBar.finish();
  if ([911, 906, 905, 908, 456].includes(response.data?.code)) {
    Router.push("/login");
    return {
      code: 401,
      message: "登录超时，请重新登录",
    };
  }
  return response.data;
}, err);
// request interceptor
service.interceptors.request.use(config => {
  LoadingBar.start();
  const token = Store()?.userInfo?.token;
  // console.log(config);
  if (token && !config?.whiteList) {
    config.headers.authorization = token;
  }
  return config;
}, err);
export default service;
